package com.subfg.payment.rabiitmq.config;


import com.subfg.common.rabbitmq.constant.ExchangeApi;
import com.subfg.payment.rabiitmq.constant.QueueApi;
import com.subfg.payment.rabiitmq.constant.RoutingKeyApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    private Logger log = LoggerFactory.getLogger(RabbitMQConfig.class);
    @Autowired
    private AmqpAdmin rabbitAdmin;
    @Bean
    public void createQueueName() {
        bindingExchangeCommon();
        bindingDelayExchange();
    }

    public void bindingExchangeCommon() {
        if (rabbitAdmin.getQueueProperties(ExchangeApi.EXCHANGE_COMMON) == null) {
            log.info("在Rabbitmq中未发现此交换机, 正在进行创建");
            // topic  交换机
            TopicExchange topicExchange = new TopicExchange(ExchangeApi.EXCHANGE_COMMON);
            // 构建队列名称
            Queue logQueue = new Queue(QueueApi.PAYMENT_QUEUE_LOGGER);
            Queue paymentQueue = new Queue(QueueApi.PAYMENT_QUEUE_PAYMENT_COMMON);
            Queue refundQueue = new Queue(QueueApi.PAYMENT_QUEUE_PAYMENT_REFUND);

            // 构建队列
            rabbitAdmin.declareQueue(logQueue);
            rabbitAdmin.declareQueue(paymentQueue);
            rabbitAdmin.declareQueue(refundQueue);
            // 构建路由
            rabbitAdmin.declareExchange(topicExchange);
            // 绑定交换机
            rabbitAdmin.declareBinding(BindingBuilder.bind(logQueue).to(topicExchange).with(RoutingKeyApi.ROUTINGKEY_LOGGER));
            rabbitAdmin.declareBinding(BindingBuilder.bind(paymentQueue).to(topicExchange).with(RoutingKeyApi.ROUTING_PAYEMNT));
            rabbitAdmin.declareBinding(BindingBuilder.bind(refundQueue).to(topicExchange).with(RoutingKeyApi.ROUTING_REFUND));
        }
    }
    /** 延迟队列 **/
    public void bindingDelayExchange() {
        // 自定义队列交换机类型 为延迟   durable 是否为持久,为true 服务器重启时不会丢失相关信息
        CustomExchange exchange = new CustomExchange(ExchangeApi.EXCHANGE_DELAYED, "x-delayed-message", true, false, getDelayedExchangeType("topic"));
        Queue delayOrderQueue = new Queue(QueueApi.PAYMENT_QUEUE_PAYMENT_DELAY);
        rabbitAdmin.declareQueue(delayOrderQueue);
        rabbitAdmin.declareExchange(exchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(delayOrderQueue).to(exchange).with(RoutingKeyApi.DELAY_PAYMEN).noargs());
    }

    /**
     * 设置rabbit mq 交换机类型为延迟
     *
     * @param exchangeType 交换机类型 topic, direct, fanout, headers,
     * @return
     */
    private Map<String, Object> getDelayedExchangeType(String exchangeType) {
        Map<String, Object> exchangeMap = new HashMap<>();
        exchangeMap.put("x-delayed-type", exchangeType);
        return exchangeMap;
    }

}
